var app = getApp();
var common_Js = require("../../component/common.js"), fetchApi = require("../../utils/httpPost.js")
import Toast from '../../component/vant/toast/toast';
import Dialog from '../../component/vant/dialog/dialog';
import Notify from '../../component/vant/notify/notify';
const CryptoJS = require("../../utils/aesUtil.js")
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgurl:app.getImgUrl(),
    userInfo: {},
    hasUserInfo: false,
    current: 0,
    currentTabId: 0,
    pageIndex: 1,
    pageSize: 10,
    tabs: [],//标题tab菜单
    loading: false,
    netWork: true,
    isLoading: true,
    hotword:'请输入商品名称',
    isLogin:0,
    autoplay:true,
    wd:0,
    jd:0,
    banners:[],
    menus:[],
    notices:[],
    sections: [],//内容行集合
    is_show_search:0,
    ag_id:0,//邀请人id
    isiphonex: app.globalData.isiphonex,
    isxiaomi: app.globalData.isxiaomi,
    specialMenuRowCount:2,
    propertyMenuRowCount:5,
    normalMenuRowCount:5,
    rowCount:5,
    first_page_filter_css:'',
    is_change_location:0,
    location_address:'',
    city_id: 0,
    city_name: "",
    action:'',
    active:0,
    activeTypeList:[],
    activeList:[],
    estate_id:0,
    estate_name:'',
    band_estate_count:0,
    estate_state:0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // var o = getCurrentPages().pop();
    console.log('onLoad options',options)
    if (options != undefined && options.q) {
      var q = decodeURIComponent(options.q) // 获取到二维码原始链接内容
      q = "?" + q.split("?")[1];
      this.data.query = q;
      console.log('q', q)
      options = common_Js.getQueryVariable(q);
    }
    app.setStorageSync("ag_id",0);
    if(options!=undefined && options.ag_id){
      var isLogin = app.getStorageSync("isLogin");
      if(isLogin == undefined || isLogin == 0 || isLogin == ''){
      }
      this.data.ag_id = parseInt(options.ag_id);
      app.setStorageSync("ag_id",this.data.ag_id);
    }
    this.data.jd = app.getStorageSync("lng")!=undefined && app.getStorageSync("lng")!='' ?app.getStorageSync("lng") : 0;
    this.data.wd = app.getStorageSync("lat")!=undefined && app.getStorageSync("lat")!='' ?app.getStorageSync("lat") : 0;

    this.onHttpInit();
    
    wx.getPrivacySetting({
      success: res => {
        console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
        if (res.needAuthorization) {
          // 需要弹出隐私协议
        } else {
        }
      },
      fail: () => {},
      complete: () => {}
    })
  },
  onShow: function () {
    var that = this;
    that.data.pageIndex = 1;

    var isLogin = app.getStorageSync('isLogin');
    that.setData({ isLogin: isLogin})
    if(isLogin){
      if(isLogin == 1){
        var user_id = app.getStorageSync('user_id');
        if(user_id > 0){
          app.getUserInfoById(user_id)
        }else{
          wx.navigateTo({
            url: '/pages/login/index',
          })
        }
      }
    }else{
      app.setStorageSync('isLogin', 0);
    }    
    var isLogin = app.getStorageSync('isLogin');

    var band_estate_room = app.getStorageSync('band_estate_count');
    console.log('band_estate_room',band_estate_room)
    this.setData({
      band_estate_count: band_estate_room,
    })




    if(this.data.action == 'change_city'){
      this.data.pageIndex = 1;
      this.setData({
        isLoading:true,
        banners:[],
        menus:[],
        notices:[],
        sections: [],//内容行集合
      })
      this.onHttpInit();
    } else if(this.data.action == 'change_estate'){
      console.log('this.data.action  change_estate ', this.data.action)
    }else{
      console.log('this.data.action  else ', this.data.action)
      var estate_name = app.getStorageSync('estate_name');
      this.data.estate_state = app.getStorageSync('estate_state');
      this.setData({
        estate_name: estate_name
      })
    }
  },
  
//   modalcnt:function  ()  {
//     var that = this;
//     //获取经纬度  
//     wx.getLocation({
//       type:  'gcj02',
//       success:  function  (res)  {
//         console.log('modalcnt', res)
//         var latitude = res.latitude
//         var longitude = res.longitude
//         that.data.wd = latitude//纬度
//         that.data.jd = longitude//经度
//         that.setData({
//           wd : latitude,
//           jd : longitude
//         })
//         app.setStorageSync("lng",longitude);
//         app.setStorageSync("lat",latitude);
//         that.onHttpInit();
//       },fail:function(res){
//         that.data.wd = 0
//         that.data.jd = 0
//         app.setStorageSync("lng",0);
//         app.setStorageSync("lat",0);
//         that.onHttpInit()
//       }
//     })
//   },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this;
    fetchApi.httpPost('/index/index', {
      pageSize: that.data.pageSize,
      pageIndex: that.data.pageIndex,
      longitude: that.data.jd,
      latitude: that.data.wd,
      city_id: that.data.city_id,
      city_name:that.data.city_name,
    }, function (res) {
      console.log('首页数据',res)
      if (res.data.code == 0) {
        that.data.pageIndex = that.data.pageIndex+ 1;
        that.setData({
            banners:res.data.data.banners,
            menus: res.data.data.menuList,
            sections: res.data.data.sections,
            notices: res.data.data.notices,
            is_show_search:res.data.data.is_show_search,
            propertyMenuRowCount : res.data.data.propertyMenuRowCount,
            normalMenuRowCount : res.data.data.normalMenuRowCount,
            rowCount : res.data.data.rowCount,
            first_page_filter_css : res.data.data.first_page_filter_css,
            is_change_location : res.data.data.is_change_location,
            location_address : res.data.data.location_address,
            city_name: res.data.data.city_name,
            activeTypeList: res.data.data.activeTypeList,
            activeList: res.data.data.activeList,
        })
        that.setData({
          isLoading: false, loading: true, netWork: true,
        });
        that.tipLocation(res.data.data.is_change_location,res.data.data.location_address);
      } else {
        that.setData({ isLoading: false, loading: true, netWork: true })
      }
      // complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, function () {
        that.setData({  isLoading: false,  loading: true,  netWork: true, }) 
    })
  },
  goSearch(res){
    console.log('goSearch')
    wx.navigateTo({
      url: '/pagesMer/pages/search/search',
    })
  },
  goNotice(res){
    console.log('goNotice',res)
    var id = res.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/notice/detail/index?id='+ id,
    })
  },
  chooseEstate(e){
    wx.navigateTo({
      url: '/pages/estate/list/index?is_change=1&is_band=1',
    })
  },
  goShowBuild(){
    Toast('工程师正加紧建设中...');
  },
  goActiveList(){
    wx.navigateTo({
      url: '/pagesProperty/pages/active/list/index',
    })
  },  
  callPlatform(e){
    let phone = app.getStorageSync('estate_telphone');
    if(phone!=undefined &&phone!=''){
      wx.makePhoneCall({
        phoneNumber: phone,
      })
    }else{
      Toast('暂未开通电话客服')
    }
  },
  tipLocation(is_change_location,location_address){
    console.log('tipLocation',is_change_location)
    var that = this;
    if(is_change_location == 1){
      var message = "您当前定位在" + location_address+"，是否要切换？";
      Dialog.confirm({
        title: '定位切换',
        message
      }).then(() => {
        that.onHttpUpdateLocation();
      })
      .catch(() => {
        Dialog.close();
      });
    }
  },
  /**
   * 获取页面数据的 http请求
    a.httpPost('/titleMenu/list', {
   */
  onHttpUpdateLocation: function () {
    var that = this;
    fetchApi.httpPost('/user/updateLocation',{
      longitude: that.data.jd,
      latitude: that.data.wd,
    }, function (res) {
      console.log("切换定位城市", res)
      if(res.data.code == 0){
        that.data.pageIndex = 1;
        that.setData({
          isLoading:true,
          banners:[],
          menus:[],
          notices:[],
          sections: [],//内容行集合
        })
        that.onHttpInit();
      }else{
        Toast(res.data.msg);
      }
    },function(){})
  },
  pushToDetail: function (e) {
    console.log("pushToDetail.e", e)
    var itemData = e.detail.target.dataset.item;
    console.log("itemData", itemData)
    // 链接的类型 0 - 单商品id 1 - 商品页（title_menu_id）2 - 团购商品id 3 - 团购商品页id  4 - 优惠券id
    console.log("itemData.linkType", itemData.linkType)
    if (itemData.linkType == 'product') {//
      wx.navigateTo({
        url: '/pages/product/detail/index?id=' + itemData.linkId + '&from=appHome'
      });
    }
  },
  goSelectCity(){
    wx.navigateTo({
      url: '/pagesPlatform/pages/city/index',
    })
  },
  goSearch(){
    wx.navigateTo({
      url: '/pagesMer/pages/search/search',
    })
  },
  onSearch(val){
    console.log('onSearch',val)
    this.data.keyword = val.detail;
    this.onHttpInit()
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作  下拉刷新
   */
  onPullDownRefresh: function () {
    this.data.pageIndex = 1
    this.setData({
      loading: false,
      netWork: false,
      isLoading: true
    })
    this.onHttpInit()
  },
  /**
   * 页面上拉触底事件的处理函数    加载更多
   */
  onReachBottom: function () {
    // this.onHttpLoadMore()
  },
  /**
   * 获取页面数据的 http请求
    a.httpPost('/titleMenu/list', {
   */
  onHttpLoadMore: function () {
    var that = this;
    fetchApi.httpPost('/titleMenu/list',{
      title_menu_id:9,
      pageIndex: that.data.pageIndex,
      pageSize: that.data.pageSize,
    }, function (res) {
      console.log("加载更多数据", res)
      if(res.data.totalcount > 0){
        that.data.pageIndex = that.data.pageIndex + 1;
        var sections = res.data.data.sections;
        for (var index in sections) {
          that.data.sections.splice(that.data.sections.length, 0, sections[index]);
        }
        that.setData({ sections: that.data.sections });
      }
      that.setData({ isLoading: false, loading: true, netWork: true })
      // complete
      wx.stopPullDownRefresh(); //停止下拉刷新
    },function(){})
  },
  scanCode: function (res) {
    console.log('scanCode res',res)
    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    var estate_id = app.getStorageSync("estate_id");
    that.data.from_page = 'scancode';
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else if(estate_id == 0){
      Toast.fail('请先绑定社区')
    } else {
      wx.scanCode({
        success: (res) => {
          console.log("扫码结果", res);
          var qrcontent = res.result;
          console.log('扫码结果',qrcontent)
          var json_param = {}
          if(qrcontent.indexOf('https://') >= 0){
            var q = "?" + qrcontent.split("?")[1];
            var json_param = common_Js.getQueryVariable(q);
            if(qrcontent.indexOf('mer/pay') >= 0){
              wx.navigateTo({ url: '/pages/pay/merOffline/index?no=' + json_param.no })
            } else if(qrcontent.indexOf('room/info') >= 0){
              wx.navigateTo({ url: '/pagesProperty/pages/feeList/index?id=' + json_param.id })
            }
             else{
              Toast.fail("当前二维码无效");
            }
          }
        },
        fail: (res) => { console.log(res); }
      })
    }
  },
  handleActive(e){
    let type = e.currentTarget.dataset.type;
    let index = e.currentTarget.dataset.index;
    this.setData({
      active: index
    })
    var that = this;
    fetchApi.httpPost('/active/list', {
      active_type: type,
      pageIndex: 1,
      pageSize: 5,
    }, function (res) {
      console.log("活动列表数据", res)
      if (res.data.code == 0) {
        that.setData({
          activeList: res.data.data.activeList
        })
      }
    }, function (res) {
        // that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    var user_id = app.getStorageSync("user_id");
    console.log("转发成功 user_id",user_id)
    return {
      title: "精彩e家",
      path: '/pages/home/home?ag_id='+user_id,
      success: function (res) {
        console.log(res, "转发成功")
      },
      fail: function (res) {
        console.log(res, "转发失败")
      }
    }
  },  
})